<!-- 安全审计页面 -->
<template>
  <div class="security-audit">
    <!-- 顶部工具栏 -->
    <div class="audit-header">
      <div class="header-left">
        <h1 class="audit-title">
          <el-icon class="title-icon"><CircleCheckFilled /></el-icon>
          安全审计中心
        </h1>
        <div class="system-info">
          <el-tag type="info" size="small">系统监控</el-tag>
          <el-tag type="success" size="small" v-if="systemStatus.secure">
            <el-icon><Check /></el-icon>
            安全状态正常
          </el-tag>
          <el-tag type="warning" size="small" v-else>
            <el-icon><Warning /></el-icon>
            存在安全风险
          </el-tag>
        </div>
      </div>

      <div class="header-actions">
        <el-button-group class="action-group">
          <el-button size="small" @click="refreshAuditData">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
          <el-button size="small" @click="exportAuditReport">
            <el-icon><Download /></el-icon>
            导出报告
          </el-button>
          <el-button size="small" type="primary" @click="generateSecurityReport">
            <el-icon><Document /></el-icon>
            生成报告
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="audit-content">
      <!-- 权限矩阵管理器 -->
      <div class="audit-panel matrix-panel">
        <div class="panel-header">
          <h2 class="panel-title">
            <el-icon><UserFilled /></el-icon>
            权限矩阵管理器
          </h2>
          <div class="panel-actions">
            <el-button size="small" text @click="refreshPermissionMatrix">
              <el-icon><Refresh /></el-icon>
            </el-button>
            <el-button size="small" text @click="editPermissions">
              <el-icon><Edit /></el-icon>
            </el-button>
          </div>
        </div>
        <div class="panel-content">
          <PermissionMatrix 
            :matrixData="permissionData"
            @roleChanged="handleRoleChange"
            @permissionUpdated="handlePermissionUpdate"
          />
        </div>
      </div>

      <!-- 操作追溯时间线 -->
      <div class="audit-panel timeline-panel">
        <div class="panel-header">
          <h2 class="panel-title">
            <el-icon><Clock /></el-icon>
            操作追溯时间线
          </h2>
          <div class="panel-actions">
            <el-date-picker
              v-model="timelineFilter.dateRange"
              type="datetimerange"
              size="small"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="filterTimelineData"
              class="date-filter"
            />
            <el-select
              v-model="timelineFilter.operationType"
              placeholder="操作类型" 
              size="small"
              clearable
              @change="filterTimelineData"
              class="type-filter"
            >
              <el-option label="全部" value="" />
              <el-option label="数据访问" value="data_access" />
              <el-option label="权限变更" value="permission_change" />
              <el-option label="系统配置" value="system_config" />
              <el-option label="用户登录" value="user_login" />
            </el-select>
          </div>
        </div>
        <div class="panel-content">
          <OperationTimeline 
            :timelineData="filteredTimelineData"
            :loading="timelineLoading"
            @playback="handleOperationPlayback"
            @exportLog="handleExportLog"
          />
        </div>
      </div>
    </div>

    <!-- 底部统计栏 -->
    <div class="audit-footer">
      <div class="stats-left">
        <div class="stat-item">
          <el-icon><User /></el-icon>
          <span>活跃用户: {{ statistics.activeUsers }}</span>
        </div>
        <div class="stat-item">
          <el-icon><Key /></el-icon>
          <span>权限变更: {{ statistics.permissionChanges }}</span>
        </div>
        <div class="stat-item">
          <el-icon><View /></el-icon>
          <span>数据访问: {{ statistics.dataAccess }}</span>
        </div>
      </div>

      <div class="stats-right">
        <div class="security-level">
          <el-icon class="security-icon" :class="{ secure: systemStatus.secure }"><Lock /></el-icon>
          <span class="security-text">安全等级: {{ systemStatus.level }}</span>
        </div>
        <div class="last-update">
          <el-icon><Clock /></el-icon>
          <span>最后更新: {{ formatTime(lastUpdateTime) }}</span>
        </div>
      </div>
    </div>

    <!-- 快捷操作面板 -->
    <transition name="fade">
      <div v-if="showQuickPanel" class="quick-panel">
        <div class="quick-title">快捷操作</div>
        <div class="quick-actions">
          <el-button size="small" text @click="clearAuditLogs">
            <el-icon><Delete /></el-icon>
            清理日志
          </el-button>
          <el-button size="small" text @click="backupAuditData">
            <el-icon><FolderAdd /></el-icon>
            备份数据
          </el-button>
          <el-button size="small" text @click="securityScan">
            <el-icon><Search /></el-icon>
            安全扫描
          </el-button>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Lock,
  Check,
  Warning,
  Refresh,
  Download,
  Document,
  UserFilled,
  Edit,
  Clock,
  User,
  Key,
  View,
  Delete,
  FolderAdd,
  Search,
  CircleCheckFilled
} from '@element-plus/icons-vue'

// 导入子组件
import PermissionMatrix from './components/audit/PermissionMatrix.vue'
import OperationTimeline from './components/audit/OperationTimeline.vue'

// 系统状态
const systemStatus = reactive({
  secure: true,
  level: '高',
  lastScan: new Date()
})

// 权限数据
const permissionData = ref([])

// 时间线过滤器
const timelineFilter = reactive({
  dateRange: null,
  operationType: ''
})

// 时间线数据
const timelineData = ref([])
const timelineLoading = ref(false)
const showQuickPanel = ref(false)
const lastUpdateTime = ref(new Date())

// 统计数据
const statistics = reactive({
  activeUsers: 28,
  permissionChanges: 5,
  dataAccess: 142
})

// 计算属性
const filteredTimelineData = computed(() => {
  let filtered = timelineData.value

  if (timelineFilter.dateRange && timelineFilter.dateRange.length === 2) {
    const [start, end] = timelineFilter.dateRange
    filtered = filtered.filter(item => {
      const itemTime = new Date(item.timestamp)
      return itemTime >= start && itemTime <= end
    })
  }

  if (timelineFilter.operationType) {
    filtered = filtered.filter(item => item.type === timelineFilter.operationType)
  }

  return filtered
})

// 顶部工具栏操作
const refreshAuditData = async () => {
  timelineLoading.value = true
  try {
    // 模拟刷新数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    await loadAuditData()
    lastUpdateTime.value = new Date()
    ElMessage.success('审计数据已刷新')
  } catch (error) {
    ElMessage.error('刷新失败')
  } finally {
    timelineLoading.value = false
  }
}

const exportAuditReport = () => {
  const reportData = {
    systemStatus: systemStatus,
    statistics: statistics,
    permissionMatrix: permissionData.value,
    operationLog: timelineData.value,
    exportTime: new Date().toISOString()
  }

  const dataStr = JSON.stringify(reportData, null, 2)
  const blob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(blob)

  const link = document.createElement('a')
  link.href = url
  link.download = `security_audit_report_${Date.now()}.json`
  link.click()

  URL.revokeObjectURL(url)
  ElMessage.success('审计报告已导出')
}

const generateSecurityReport = () => {
  ElMessage.info('正在生成安全报告...')
  // 模拟报告生成
  setTimeout(() => {
    ElMessage.success('安全报告生成完成')
  }, 2000)
}

// 权限矩阵操作
const refreshPermissionMatrix = async () => {
  try {
    await loadPermissionData()
    ElMessage.success('权限数据已刷新')
  } catch (error) {
    ElMessage.error('刷新权限数据失败')
  }
}

const editPermissions = () => {
  ElMessage.info('权限编辑功能开发中...')
}

const handleRoleChange = (roleData) => {
  ElMessage.success(`角色 "${roleData.name}" 配置已更新`)
  statistics.permissionChanges++
}

const handlePermissionUpdate = (permissionUpdate) => {
  ElMessage.success('权限更新成功')
  statistics.permissionChanges++
}

// 时间线操作
const filterTimelineData = () => {
  // 过滤逻辑在计算属性中处理
}

const handleOperationPlayback = (operation) => {
  ElMessage.info(`正在回放操作: ${operation.description}`)
}

const handleExportLog = (logData) => {
  const dataStr = JSON.stringify(logData, null, 2)
  const blob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(blob)

  const link = document.createElement('a')
  link.href = url
  link.download = `operation_log_${Date.now()}.json`
  link.click()

  URL.revokeObjectURL(url)
  ElMessage.success('操作日志已导出')
}

// 快捷操作
const clearAuditLogs = async () => {
  try {
    await ElMessageBox.confirm('确定要清理审计日志吗？此操作不可恢复。', '确认清理', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 模拟清理操作
    await new Promise(resolve => setTimeout(resolve, 1000))
    timelineData.value = []
    ElMessage.success('审计日志已清理')
    showQuickPanel.value = false
  } catch {
    // 用户取消
  }
}

const backupAuditData = () => {
  ElMessage.info('正在备份审计数据...')
  setTimeout(() => {
    ElMessage.success('审计数据备份完成')
    showQuickPanel.value = false
  }, 1500)
}

const securityScan = () => {
  ElMessage.info('正在执行安全扫描...')
  setTimeout(() => {
    systemStatus.secure = Math.random() > 0.3
    systemStatus.level = systemStatus.secure ? '高' : '中'
    systemStatus.lastScan = new Date()
    ElMessage.success('安全扫描完成')
    showQuickPanel.value = false
  }, 2000)
}

// 工具函数
const formatTime = (time) => {
  return new Date(time).toLocaleString('zh-CN')
}

// 数据加载
const loadAuditData = async () => {
  await Promise.all([
    loadPermissionData(),
    loadTimelineData()
  ])
}

const loadPermissionData = async () => {
  // 模拟加载权限数据
  permissionData.value = [
    {
      role: 'commander',
      name: '指挥员',
      permissions: {
        dataAccess: true,
        systemConfig: true,
        userManagement: true,
        securityAudit: true
      }
    },
    {
      role: 'operator',
      name: '操作员',
      permissions: {
        dataAccess: true,
        systemConfig: false,
        userManagement: false,
        securityAudit: false
      }
    }
  ]
}

const loadTimelineData = async () => {
  // 模拟加载时间线数据
  timelineData.value = [
    {
      id: 1,
      type: 'user_login',
      user: '张三',
      description: '用户登录系统',
      timestamp: new Date(Date.now() - 1000 * 60 * 30),
      result: 'success',
      ip: '192.168.1.100'
    },
    {
      id: 2,
      type: 'data_access',
      user: '李四',
      description: '访问电磁数据集 EMD_001',
      timestamp: new Date(Date.now() - 1000 * 60 * 60),
      result: 'success',
      details: '读取权限'
    },
    {
      id: 3,
      type: 'permission_change',
      user: '管理员',
      description: '修改操作员角色权限',
      timestamp: new Date(Date.now() - 1000 * 60 * 90),
      result: 'success',
      changes: ['数据访问权限']
    }
  ]
}

// 键盘快捷键
const handleKeydown = (event) => {
  if (event.ctrlKey && event.key === 'r') {
    event.preventDefault()
    refreshAuditData()
  } else if (event.key === 'Escape') {
    showQuickPanel.value = false
  } else if (event.key === ' ' && !event.target.matches('input, textarea')) {
    event.preventDefault()
    showQuickPanel.value = !showQuickPanel.value
  }
}

// 生命周期
onMounted(async () => {
  document.addEventListener('keydown', handleKeydown)
  await loadAuditData()
  
  // 定期更新统计数据
  setInterval(() => {
    statistics.activeUsers = Math.floor(Math.random() * 50) + 20
    statistics.dataAccess += Math.floor(Math.random() * 5)
    lastUpdateTime.value = new Date()
  }, 30000)
})

onBeforeUnmount(() => {
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
/* 主容器 - 适配侧边栏布局 */
.security-audit {
  width: 96vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #1f2d3d;
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 4vw;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 顶部工具栏 */
.audit-header {
  height: 7vh;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 2vw;
  background: linear-gradient(135deg, #263445, #1f2d3d);
  border-bottom: 1px solid #2d3a4b;
  box-shadow: 0 0.2vh 0.8vh rgba(0, 0, 0, 0.3);
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 2vw;
}

.audit-title {
  margin: 0;
  font-size: 1.4rem;
  font-weight: 600;
  color: #bfcbd9;
  display: flex;
  align-items: center;
  gap: 1vw;
}

.title-icon {
  font-size: 1.6rem;
  color: var(--el-color-primary);
}

.system-info {
  display: flex;
  align-items: center;
  gap: 0.8vw;
}

.header-actions {
  display: flex;
  gap: 1vw;
}

.action-group .el-button {
  height: 3.5vh;
  font-size: 0.85rem;
}

/* 主内容区域 */
.audit-content {
  flex: 1;
  display: flex;
  gap: 1.5vh;
  padding: 1.5vh 2vw;
  overflow: hidden;
  min-height: 0;
}

/* 审计面板 */
.audit-panel {
  background: #263445;
  border: 1px solid #2d3a4b;
  border-radius: 1vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 0.5vh 1.5vh rgba(0, 0, 0, 0.2);
}

.matrix-panel {
  flex: 1;
  min-width: 45vw;
}

.timeline-panel {
  flex: 1;
  min-width: 45vw;
}

.panel-header {
  height: 6vh;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 2vw;
  background: #1f2d3d;
  border-bottom: 1px solid #2d3a4b;
}

.panel-title {
  margin: 0;
  font-size: 1.1rem;
  font-weight: 600;
  color: #bfcbd9;
  display: flex;
  align-items: center;
  gap: 0.8vw;
}

.panel-actions {
  display: flex;
  align-items: center;
  gap: 1vw;
}

.date-filter {
  width: 20vw;
  max-width: 280px;
}

.type-filter {
  width: 8vw;
  min-width: 100px;
}

.panel-content {
  flex: 1;
  padding: 2vh 2vw;
  overflow: auto;
}

/* 底部统计栏 */
.audit-footer {
  height: 5vh;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 2vw;
  background: #1f2d3d;
  border-top: 1px solid #2d3a4b;
  font-size: 0.8rem;
}

.stats-left, .stats-right {
  display: flex;
  align-items: center;
  gap: 2vw;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 0.5vw;
  color: #bfcbd9;
}

.security-level {
  display: flex;
  align-items: center;
  gap: 0.5vw;
}

.security-icon {
  font-size: 0.9rem;
  color: var(--el-color-warning);
  transition: color 0.3s ease;
}

.security-icon.secure {
  color: var(--el-color-success);
}

.security-text, .last-update span {
  color: #bfcbd9;
}

.last-update {
  display: flex;
  align-items: center;
  gap: 0.5vw;
  color: #bfcbd9;
}

/* 快捷操作面板 */
.quick-panel {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #263445;
  border: 1px solid #2d3a4b;
  border-radius: 1vh;
  padding: 2vh;
  box-shadow: 0 1vh 3vh rgba(0, 0, 0, 0.5);
  z-index: 2000;
  min-width: 25vw;
}

.quick-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #bfcbd9;
  margin-bottom: 1.5vh;
  text-align: center;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 1vh;
}

.quick-actions .el-button {
  justify-content: flex-start;
  height: 4vh;
}

/* 过渡动画 */
.fade-enter-active, .fade-leave-active {
  transition: all 0.3s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
  transform: translate(-50%, -50%) scale(0.9);
}

/* 滚动条样式 */
.panel-content::-webkit-scrollbar {
  width: 8px;
}

.panel-content::-webkit-scrollbar-track {
  background: #1f2d3d;
  border-radius: 4px;
}

.panel-content::-webkit-scrollbar-thumb {
  background: #2d3a4b;
  border-radius: 4px;
  transition: background 0.3s ease;
}

.panel-content::-webkit-scrollbar-thumb:hover {
  background: #409EFF;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .audit-content {
    flex-direction: column;
  }
  
  .matrix-panel, .timeline-panel {
    min-width: auto;
    height: 40vh;
  }
}

@media (max-width: 1200px) {
  .audit-title {
    font-size: 1.2rem;
  }

  .system-info {
    display: none;
  }

  .stats-left .stat-item:nth-child(n+3) {
    display: none;
  }
}

@media (max-width: 768px) {
  .audit-header {
    height: 8vh;
  }

  .quick-panel {
    min-width: 80vw;
  }

  .date-filter {
    width: 30vw;
  }

  .type-filter {
    width: 15vw;
  }
}

/* Element Plus 深色主题覆盖 */
.security-audit :deep(.el-button) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

.security-audit :deep(.el-button:hover) {
  background: #2d3a4b !important;
  border-color: #409EFF !important;
  color: #409EFF !important;
}

.security-audit :deep(.el-button--primary) {
  background: #409EFF !important;
  border-color: #409EFF !important;
  color: #ffffff !important;
}

.security-audit :deep(.el-tag) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

.security-audit :deep(.el-tag--success) {
  background: #1f4838 !important;
  border-color: #2d5a41 !important;
  color: #67C23A !important;
}

.security-audit :deep(.el-tag--warning) {
  background: #4a3c1d !important;
  border-color: #6b5423 !important;
  color: #E6A23C !important;
}

.security-audit :deep(.el-input__wrapper) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  box-shadow: 0 0 0 1px #2d3a4b inset !important;
}

.security-audit :deep(.el-input__inner) {
  background: #263445 !important;
  color: #bfcbd9 !important;
}

.security-audit :deep(.el-select .el-input__wrapper) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
}

.security-audit :deep(*) {
  color: #bfcbd9;
}
</style>

<!-- 全局样式覆盖 -->
<style>
.el-select-dropdown {
  background: #263445 !important;
  border-color: #2d3a4b !important;
}

.el-select-dropdown__item {
  background: #263445 !important;
  color: #bfcbd9 !important;
}

.el-select-dropdown__item:hover {
  background: #2d3a4b !important;
  color: #409EFF !important;
}

.el-picker-panel {
  background: #263445 !important;
  border-color: #2d3a4b !important;
}

.el-date-picker__header {
  background: #1f2d3d !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

.el-picker-panel__content {
  background: #263445 !important;
}

.el-date-table td {
  color: #bfcbd9 !important;
}

.el-date-table td.available:hover {
  background: #2d3a4b !important;
  color: #409EFF !important;
}

.el-date-table td.current {
  background: #409EFF !important;
  color: #ffffff !important;
}
</style>